<template>
  <div class="user-manage">
    <el-form :inline="true" :model="formData" :rules="rules" ref="formData">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请填写姓名"
          autocomplete="off"
          :clearable="true"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="formData.phone"
          placeholder="请填写手机号"
          autocomplete="off"
          :clearable="true"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="formData.status"
          placeholder="状态"
          autocomplete="off"
          :clearable="true"
          :popper-append-to-body="false"
          style="width: 100px"
        >
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getUserList">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
        <el-button type="primary" @click="dialogFormVisible = true"
          >添加用户</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 添加用户 -->
    <el-dialog
      title="添加用户"
      width="38%"
      :visible.sync="dialogFormVisible"
      @close="closeDialog"
    >
      <el-form
        :model="insertForm"
        :rules="insertRules"
        ref="insertForm"
        class="insertForm"
      >
        <el-form-item>
          <div class="insert-avatar">
            <div class="avatar">
              <img :src="insertForm.avatar || defaultAvatar" alt="" />
              <el-upload
                action="zhanweifu"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="changeFile"
              >
                <span v-loading="uploadLoading"></span>
              </el-upload>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label="登录名"
          :label-width="formLabelWidth"
          prop="userName"
        >
          <el-input
            v-model="insertForm.userName"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="userPwd">
          <el-input
            v-model="insertForm.userPwd"
            type="password"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input
            v-model="insertForm.name"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
          <el-select
            v-model="insertForm.gender"
            autocomplete="off"
            :clearable="true"
            :popper-append-to-body="false"
            style="width: 100px"
          >
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
            <el-option label="保密" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input
            v-model="insertForm.phone"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <el-select
            v-model="insertForm.status"
            autocomplete="off"
            :clearable="true"
            :popper-append-to-body="false"
            style="width: 100px"
          >
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="insert" :loading="insertLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 表格 -->
    <div class="admin-table">
      <div class="batch-btn">
        <el-button
          type="danger"
          size="mini"
          @click="batchDelete"
          v-show="this.multipleSelection.length > 0"
          >批量删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="46" align="center">
        </el-table-column>
        <el-table-column
          type="index"
          width="50"
          :index="indexConfig"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="userName"
          label="登录名"
          width="90"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="userPwd" label="密码" width="116" align="center">
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="96" align="center">
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="50" align="center">
          <template slot-scope="scope">
            <span>{{
              scope.row.gender === 1
                ? "男"
                : scope.row.gender === 2
                ? "女"
                : "保密"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号" width="110" align="center">
          <template slot-scope="scope">
            {{ scope.row.phone || "暂无手机号" }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="160" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="76" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status === 1">启用</el-tag>
            <el-tag type="danger" v-else="scope.row.status === 0">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="success"
              size="mini"
              @click="updateStatus(scope.row, 1)"
              >启动</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="updateStatus(scope.row, 0)"
              >禁用</el-button
            >
            <el-button type="danger" size="mini" @click="del(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        v-show="tableData.length > 0"
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        :pager-count="7"
        style="text-align: right; margin-top: 24px"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { uploadFile } from "@/api/common";
import {
  insertUser,
  getUserList,
  updateUserStatus,
  batchDeleteUser,
} from "@/api/admin/user";
import defaultAvatar from "@/assets/default.jpg";
export default {
  name: "UserView",
  data() {
    return {
      // 默认头像
      defaultAvatar,
      formData: {
        name: "",
        phone: "",
        status: "",
      },
      insertForm: {
        userName: "",
        userPwd: "",
        name: "",
        gender: "",
        phone: "",
        avatar: "",
        status: "",
      },
      rules: {
        name: [{ validator: this.customValidator, trigger: "blur" }],
        phone: [{ validator: this.customValidator, trigger: "blur" }],
        status: [{ validator: this.customValidator, trigger: "blur" }],
      },
      insertRules: {
        userName: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        userPwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, max: 11, message: "请输入11位手机号", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确格式的手机号",
            trigger: "blur",
          },
        ],
        status: { required: true, message: "请选择状态", trigger: "change" },
      },
      // 获取的用户列表
      tableData: [],
      // 表格所选列表
      multipleSelection: [],
      page: 1,
      pageSize: 8,
      total: 0,
      currentPage: 1,
      formLabelWidth: "120px",
      tableLoading: false,
      dialogFormVisible: false,
      insertLoading: false,
      uploadLoading: false,
    };
  },
  created() {
    this.getDataList();
  },
  methods: {
    // 自定义校验规则
    customValidator(rule, value, callback) {
      const { name, phone, status } = this.formData;
      if (!name && !phone && !status) {
        callback(new Error("请填写信息"));
      } else {
        callback();
      }
    },
    // 查询用户列表
    getUserList() {
      this.$refs.formData.validate(async (v) => {
        if (v) {
          this.page = 1;
          this.getDataList();
        }
      });
    },
    // 清空
    clear() {
      this.page = 1;
      this.currentPage = 1;
      // 清空表单
      this.$refs.formData.resetFields();
      this.getDataList();
    },
    // 添加用户
    insert() {
      this.$refs.insertForm.validate(async (v) => {
        if (v) {
          try {
            this.insertLoading = true;
            const res = await insertUser(this.insertForm);
            this.dialogFormVisible = false;
            this.getDataList();
          } finally {
            this.insertLoading = false;
          }
        }
      });
    },
    // 关闭弹窗
    closeDialog() {
      this.insertLoading = false;
      this.insertForm.avatar = "";
      this.$refs.insertForm.resetFields();
    },
    // 配置表格索引
    indexConfig(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    // 当选项发生变化触发
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 分页查询
    handleCurrentChange(page) {
      this.page = page;
      this.currentPage = page;
      this.getDataList();
    },
    // 获取数据
    async getDataList() {
      try {
        this.tableLoading = true;
        const res = await getUserList({
          ...this.formData,
          page: this.page,
          pageSize: this.pageSize,
        });
        this.tableData = res.data.records;
        this.total = res.data.total;
      } finally {
        this.tableLoading = false;
      }
    },
    // 时间格式判断
    padZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 时间格式化
    formatDate(timeArray) {
      if (!timeArray) return "暂无时间";
      let year = timeArray[0];
      let month = this.padZero(timeArray[1]);
      let day = this.padZero(timeArray[2]);
      let hour = this.padZero(timeArray[3]);
      let minute = this.padZero(timeArray[4]);
      let second = this.padZero(timeArray[5]) || "00";
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    // 编辑
    edit(row) {
      // 可以依然跳转到layout中的router-view中
      this.$router.push({
        name: "AdminEditUser",
        params: { id: row.id },
      });
    },
    // 修改状态
    async updateStatus(row, status) {
      if (status === row.status) return;
      try {
        this.tableLoading = true;
        const res = await updateUserStatus({ id: row.id, status });
        await this.getDataList();
      } finally {
        this.tableLoading = false;
      }
    },
    // 删除
    async del(row) {
      this.$confirm(
        "确定删除所选数据吗？这将会删除与该用户相关的所有数据，请谨慎操作！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        const res = await batchDeleteUser([row.id]);
        await this.getDataList();
      });
    },
    // 批量删除
    async batchDelete() {
      const ids = [];
      this.multipleSelection.forEach((item) => {
        ids.push(item.id);
      });
      this.$confirm(
        "确定删除所选数据吗？这将会删除与该用户相关的所有数据，请谨慎操作！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        const res = await batchDeleteUser(ids);
        await this.getDataList();
      });
    },
    // 选择文件，上传封面
    async changeFile(file) {
      // 判断格式是否正确
      const bool = this.verifyFormat(file);
      if (!bool) {
        return;
      }
      // 上传到服务器
      // console.log("上传到服务器,返回图片路径赋值给insertForm.cover");
      this.uploadLoading = true;
      try {
        let formData = new FormData();
        // 拿到存在file中的文件存放到formData中
        formData.append("file", file.raw);
        const res = await uploadFile(formData);
        this.insertForm.avatar = res.data;
      } finally {
        this.uploadLoading = false;
      }
    },
    // 上传封面前校验格式
    verifyFormat(file) {
      const isJPG =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 jpg/jpeg/png 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="less" scoped>
.user-manage {
  width: 100%;
  height: 100%;
  background-color: #fff;
  .insertForm {
    width: 440px;
    .insert-avatar {
      position: relative;
      width: 100%;
      height: 160px;
      .avatar {
        width: 100px;
        height: 100px;
        position: relative;
        top: 50%;
        left: 60%;
        transform: translate(-50%, -50%);
        border-radius: 50%;
        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          cursor: pointer;
        }
        span {
          position: absolute;
          top: 50%;
          left: 50%;
          width: 100px;
          height: 100px;
          border-radius: 50%;
          transform: translate(-50%, -50%);
          &::before {
            content: "上传头像";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 100px;
            height: 100px;
            background-color: rgba(0, 0, 0, 0.16);
            text-align: center;
            line-height: 100px;
            border-radius: 50%;
            cursor: pointer;
            opacity: 0;
            visibility: hidden;
            z-index: 1;
            color: black;
          }
          &:hover::before {
            opacity: 1;
            visibility: visible;
          }
        }
      }
    }
  }
  .admin-table {
    .batch-btn {
      height: 28px;
      margin-bottom: 4px;
    }
  }
}
// 解决下拉框显示不完整问题
/deep/.el-select-dropdown__wrap.el-scrollbar__wrap {
  margin-bottom: 0 !important;
}

/*
解决单选框样式问题
  Blocked aria-hidden on an element because its descendant retained focus. 
  The focus must not be hidden from assistive technology users. 
  Avoid using aria-hidden on a focused element or its ancestor. 
  Consider using the inert attribute instead, which will also prevent focus. 
  For more details, see the aria-hidden section of the WAI-ARIA specification at Element with focus: input Ancestor with aria-hidden:
*/
/deep/ input[aria-hidden="true"] {
  display: none !important;
}
/deep/.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
</style>